/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: just-core
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: Aug 16, 2011 5:20:21 PM
 *
*/ 
package org.justframework.core.helper;

import java.util.HashMap;
import java.util.Map;

import org.justframework.core.router.TreeRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * host routing helper
 *
 */
public class HostRouteHelper {
	
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(HostRouteHelper.class);
	
	/**
	 * service and host router mapping
	 */
	private static Map<String, TreeRouter> serviceHostRouterMapping = new HashMap<String, TreeRouter>();
	
	/**
	 * route host by appId
	 * @param appId app id
	 * @param schema connector schema
	 * @param keys hash key or more other identifies for multi-level routing
	 * @return
	 */
	public static String route(String serviceId, String schema, String... keys){
		String result = "";
		TreeRouter router = getRouter(serviceId,schema);
		if(router == null){
			return null;
		}
		result = router.locate(keys);
		return result;
	}
	
	/**
	 * get policy router
	 * @param appId
	 * @param schema
	 * @return
	 */
	private static TreeRouter getRouter(String serviceId, String schema){
		TreeRouter router = null;
		//check if router exist for specified serviceId and schema
		String rid = serviceId+"_"+schema;
		router = serviceHostRouterMapping.get(rid);
		if(router == null){
			//create router
			String nodeList = ConfigHelper.getString("service_host_routing/"+rid+"/node_list");
			String routePolicy = ConfigHelper.getString("service_host_routing/"+rid+"/route_policy");
			router = new TreeRouter(nodeList, routePolicy);
			serviceHostRouterMapping.put(rid, router);
		}
		return router;
	}
	
}
